#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

# print("hello")

from ast import arg
import json
import os
import subprocess
import argparse

from numpy import require

# root="/home/plus/Downloads/bash-4.2"
# db="/home/plus/Downloads/bash-4.2/"+"compile_commands.json"
# output="/home/plus/include/"

parser = argparse.ArgumentParser()
parser.add_argument(
    '-dir'
    ,type=str
    ,required=True
    ,help='compile_commands.json文件所在的目录路径'
)
parser.add_argument(
    '-base'
    ,type=str
    ,required=True
    ,help='软件的根目录路径'
)
parser.add_argument(
    '-output'
    ,type=str
    ,required=True
    ,help='输出目录的路径'
)
args=parser.parse_args()
root = args.base
db = os.path.join(args.dir,'compile_commands.json') 
output = os.path.abspath(args.output)

with open(db,'r') as f:
    dbs=json.load(f)
    for entry in dbs:
        dir=entry['directory']
        args=entry['arguments']
        file=entry['file']

        p=output
        suffix=''
        if dir != root:
            if dir.find(root) == 0:
                suffix=dir[len(root):]
                if suffix[0] == '/':
                    suffix=suffix[1:]
                os.path.dirname(suffix)
                all_dir=suffix.split('/')
                for d in all_dir:
                    p=os.path.join(p,d)
                    if not os.path.exists(p):
                        os.mkdir(p)
        relative_dir = os.path.dirname(file)
        if len(relative_dir) != 0:
            p=os.path.join(p,relative_dir)
            if not os.path.exists(p):
                os.mkdir(p)
        new_args_md=[]
        new_args_mmd=[]
        for a in args:
            new_args_md.append(a)
            new_args_mmd.append(a)
            if a == 'gcc' or a == 'g++':
                new_args_md.append('-MD')
                new_args_md.append("-MF")
                new_args_md.append(os.path.join(output,suffix,file+'.md'))
                new_args_mmd.append('-MMD')
                new_args_mmd.append('-MF')
                new_args_mmd.append(os.path.join(output,suffix,file+'.mmd'))
        # print(os.path.join(output,suffix,file+'.mmd'))
        # print(' '.join(new_args_mmd))
        subprocess.call(new_args_md, cwd=dir)
        subprocess.call(new_args_mmd,cwd=dir)

